import json,pymysql
import re
from datetime import datetime
from pampy import match, HEAD, TAIL, _
from aaa.utils.conn_mysql_194 import conn_mysql

def main():
    try:
        conn_mysql('delete from weekly_check', None)
        f = open('/tmp/yzd_server_%s.xlsx' % datetime.now().__format__('%m-%d'), 'r', encoding='utf-8')
        data = json.load(f)
        for info in data:
            #     print(111,info)
            sql = "insert into weekly_check(project,ip,cpu,mem,disk,network,vda1,vdb1,service,url) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
            disk_status = info['disk_status']
            url_list = []
            service = [item for item in info if
                       item not in ['ip', 'cpu_usage', 'mem_usage', 'disk_status', 'network', 'url']]

            # 优智多服务器的服务一般只有一个，名字统一替换为'service'
            if service:
                if info['ip'] == '172.16.44.177':
                    services = info['node_service'] + '<br>' + info['manage_service'] + '<br>' + info[
                        'sdk_service'] + '<br>' + info['nginx_service']
                    info.update({'service': services})
                if len(service) == 1:
                    info.update({'service': info.pop(service[0])})
                # 如44.184有3个服务
                elif len(service) == 2:
                    services = info[service[0]] + '<br>' + info[service[1]]
                    info.update({'service': services})
                elif len(service) == 3:
                    services = info[service[0]] + '<br>' + info[service[1]] + '<br>' + info[service[2]]
                    info1 = service[0] + ';' + service[1] + service[2]
                    info.update({'service': services})
            else:
                info['service'] = ''

            if 'url' in info:
                for k, v in info['url'].items():
                    if k == 'http://mxhbc.school.cunwedu.com.cn':
                        url_list.append('梅溪湖博才学校服务' + ' ' + str(v) + '<br>')
                    url = url + k + ' ' + str(v) + '<br>'
            # 网络连接
            if info['network'] == 'Network: OK':
                info['network'] = '正常'
            # 磁盘字符串长度大于60说明有2块磁盘
            if len(disk_status) > 60:
                # 取出两块磁盘vda1,vdb1的使用率
                re_regular = re.compile('diskname: (/\w+/\w+).*USAGE: (.*)% diskname: (/\w+/\w+).*USAGE: (.*)%')
                m = match(disk_status, re_regular, lambda a, b, c, d: b + ',' + d)
                vda1, vdb1 = m.split(',')

                disk_status = info['disk_status']
                # 去掉第一个USAGE
                disk_status = re.sub('USAGE: .*% ', '', disk_status)
                # 去掉第二个USAGE
                disk_status = re.sub(' USAGE: .*%', '', disk_status)
                # 去掉第一个diskname，第二个diskname替换为换行符<br>
                disk_status = disk_status.replace('diskname: ', '', 1).replace(' diskname: ', '<br><br>')
                conn_mysql(sql, ('优智多', info['ip'], info['cpu_usage'], info['mem_usage'].strip('%'), \
                                 disk_status, info['network'], vda1, vdb1, info['service'], ''))
            else:
                re_regular = re.compile('diskname: (/\w+/\w+).*USAGE: (.*)%')
                m = match(disk_status, re_regular, lambda a, b: b)
                #         print('m',info['disk_status'])
                # 去掉USAGE
                disk_status = re.sub(' USAGE: .*%', '', disk_status)
                # 去掉diskname
                disk_status = disk_status.replace('diskname: ', '')

                conn_mysql(sql, ('优智多', info['ip'], info['cpu_usage'], info['mem_usage'].strip('%'), \
                                 disk_status, info['network'], m, '无', info['service'], ''.join(url_list)))
        print('done.')
        return [0,1]
    except Exception as e:
        print(e)
        # return '优智多巡检数据导入异常' + e
        return [1,1,e.__doc__]
